package controllers

import (
	"encoding/json"
	"fmt"
	"strings"

	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
)

type SchoolController struct {
	BaseController
}

func (c *SchoolController) Prepare() {
	c.BaseController.Prepare()
	c.Data["activeSidebarUrl"] = "/school/index"
}

func (c *SchoolController) Index() {
	c.checkAuthor("school/index")
	c.display("", "school/index_footerjs.html")
}

func (c *SchoolController) DataGrid() {
	c.checkAuthor("school/index")
	var params models.SchoolQueryParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &params)

	data, total := models.SchoolPageList(&params)
	c.jsonDataTable(total, data)
}

func (c *SchoolController) Edit() {
	c.checkAuthor("school/edit") //需要权限控制

	if c.Ctx.Input.IsPost() {
		c.save()
	}
	Id, _ := c.GetInt64(":id", 0)

	var err error

	addr := make([]string, 3)

	m := &models.Schools{}

	if Id == 0 {
	} else {
		m, err = models.GetSchoolById(Id)
		if err != nil {
			c.pageError("数据无效，请刷新后重试")
		}
		addr = strings.Split(m.Address, "-")

	}
	c.Data["addr"] = addr
	c.Data["m"] = m

	c.display("", "school/edit_footerjs.html")

}

func (c *SchoolController) save() {
	var err error
	m := models.Schools{}
	if err = c.ParseForm(&m); err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}

	cmbProvince := c.GetString("cmbProvince")
	cmbCity := c.GetString("cmbCity")
	cmbArea := c.GetString("cmbArea")

	m.Address = fmt.Sprintf("%s-%s-%s", cmbProvince, cmbCity, cmbArea)

	if m.Id == 0 {
		if _, err = m.SchoolAdd(); err == nil {
			c.jsonResult(enums.JRCodeSucc, "添加成功", m.Id)
		} else {
			c.jsonResult(enums.JRCodeFailed, err.Error(), m.Id)
		}

	} else {
		if mr, err := models.GetSchoolById(m.Id); err != nil {
			c.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
		} else {
			m.Status = mr.Status
		}

		if err = m.SchoolEdit(); err == nil {
			c.jsonResult(enums.JRCodeSucc, "编辑成功", m.Id)
		} else {
			c.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}
	}
}

func (c *SchoolController) Delete() {
	Id, err := c.GetInt64("id", 0)
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取数据失败", "")
	}
	m := models.Schools{Id: Id}
	m.Status = 0

	if err = m.SchoolEdit("status"); err == nil {
		c.jsonResult(enums.JRCodeSucc, "删除成功", m.Id)
	} else {
		c.jsonResult(enums.JRCodeFailed, "删除失败", m.Id)
	}
}
